﻿#include <QFile>
#include <QJsonObject>
#include <QDebug>
#include "JZWebPage.h"

//JZWebPage
JZWebPage::JZWebPage()
{
	m_currentContext = nullptr;
}

JZWebPage::~JZWebPage()
{
}

JZWebContext* JZWebPage::currentContext()
{
	if (m_currentContext)
		return m_currentContext;

	return baseContext();
}

void JZWebPage::setCurrentContext(JZWebContext* ctx)
{
	m_currentContext = ctx;
}

JZWebContext *JZWebPage::baseContext()
{
	return &m_context;
}

QJsonObject JZWebPage::onCommand(const QJsonObject& obj)
{
    QJsonObject ret;
    ret["code"] = 1;
    ret["error"] = "unknown command";
    return ret;
}

//JZWebWidgetPage
JZWebWidgetPage::JZWebWidgetPage()
{
	m_root = new JZWebWidgetRoot(this);
	m_widgetId = 0;
}

JZWebWidgetPage::~JZWebWidgetPage()
{

}

int JZWebWidgetPage::generateId()
{
	return m_widgetId++;
}

QString JZWebWidgetPage::render()
{
	QString style = R"(
		/* row样式 */
        .vbox-layout {
            display: flex;
			flex-direction: column;
        }
		
		/* column样式 */
        .hbox-layout {
            display: flex;
			flex-direction: row;
        }
		
		/* grid样式 */
        .grid-layout {
            display: grid;
        }
	)";

	QDomDocument doc;
		
	QDomElement htmlElement = doc.createElement("html");
	htmlElement.setAttribute("lang", "zh-CN");

	doc.appendChild(htmlElement);

	QDomElement headElement = doc.createElement("head");
	htmlElement.appendChild(headElement);

	QDomElement metaElement = doc.createElement("meta");
	metaElement.setAttribute("charset", "UTF-8");
	headElement.appendChild(metaElement);

	QDomElement titleElement = doc.createElement("title");
	QDomText titleText = doc.createTextNode("Generated HTML Page");
	titleElement.appendChild(titleText);
	headElement.appendChild(titleElement);

	QDomElement styleElement = doc.createElement("style");
	QDomText styleText = doc.createTextNode(style);
	styleElement.appendChild(styleText);
	headElement.appendChild(styleElement);

	QDomElement body = m_root->render(doc);
	htmlElement.appendChild(body);

	m_html = doc.toString();
	
	return m_html;
}

QJsonObject JZWebWidgetPage::onCommand(const QJsonObject& obj)
{
    return QJsonObject();
}

JZWebWidgetRoot* JZWebWidgetPage::root()
{
	return m_root;
}

//JZWebStaticPage
JZWebStaticPage::JZWebStaticPage()
{
}

JZWebStaticPage::~JZWebStaticPage()
{
}

QString JZWebStaticPage::render()
{
	return m_html;
}

void JZWebStaticPage::setFile(const QString& path)
{
	m_filePath = path;

	QFile file(m_filePath);
	if (!file.open(QFile::ReadOnly))
	{
		qWarning() << "JZWebStaticPage: Can't open file" << path;
		return;
	}

	m_html = QString::fromUtf8(file.readAll());
	file.close();
}